package alf.mapping.view.visuals;
import alf.common.util.SimpleFileNameFilter;
import alf.mapping.view.Env;
import alf.mapping.view.activity.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ThemeManager {
	public static final String TERRAIN = "terrain";
	public static final String SPRITES = "sprites";
	public static final String ICONS = "icons";
	private static final String PATH_SEP = "/";
	private static final String IMG_FILE_EXT = "png";
	private static final String IMG_SUFIX = ".png";
	BitmapCache cache = new BitmapCache();

	private String path = null;
	private String mod = "default";
	private String modpath = path + PATH_SEP + mod + PATH_SEP;

	private Paint paint;

	public ThemeManager(String path) {
		this.path = path;
	}

	public void setPath(String value) {
		path = value;
		this.modpath = path + PATH_SEP + mod + PATH_SEP;
		cache.clear();
	}

	public void setMod(String mod) {
		this.mod = mod;
		this.modpath = path + PATH_SEP + mod + PATH_SEP;
	}
	
	public String getResourceName(String type, String name) {
		return modpath + type + PATH_SEP + name;
	}
	
	public Bitmap getBitmap(String type , String name) {
		String imageName = getResourceName(type, name) + IMG_SUFIX;
	//	Env.debug("getBitmap: " + imageName);
		Bitmap b = cache.get(imageName);
		if (b == null) {  // file didnt exist, try "default" imahe
			imageName = getResourceName(type, "default") + IMG_SUFIX;
			b = cache.get(imageName);
			if (b == null) { // there's no default image 
				if (type.equals(SPRITES)) {
					b = BitmapFactory.decodeResource(Env.getResources(), R.drawable.box);
				} 
			}
		}
		return b;
	}

	public BitmapDrawable getBitmapDrawable(String type, String name) {
		Bitmap b = this.getBitmap(type, name);
		return new BitmapDrawable(b);
	}

	public Paint getPaint() {
		if (this.paint == null) {
			this.paint = new Paint();
			paint.setStyle(Paint.Style.STROKE);// for lines.
		}
		return this.paint;
	}

	public String[] getAvaliableImages(String group) {
		String[] lista = null;
		File dir = new File(modpath + PATH_SEP + group);
		SimpleFileNameFilter filtro_png = new SimpleFileNameFilter();
		filtro_png.setExt(IMG_FILE_EXT);
		File[] ficheros =  dir.listFiles(filtro_png);
		if (ficheros != null) {
			lista = new String[ficheros.length];
			for (int i=0;i < lista.length;i++) {
				lista[i] = ficheros[i].getName().replaceFirst(IMG_SUFIX, "");
			}
		}
		return lista;
	}

	public String[] getAvaliableThemes() {
		File dir = new File(path);
		File[] ficheros =  dir.listFiles();
		List<String> lista = null;
		if (ficheros != null) {
			lista = new ArrayList<String>();
			for (int i=0;i < ficheros.length;i++) {
				if (ficheros[i].isDirectory()) {
					lista.add(ficheros[i].getName());
				}
			}
			return lista.toArray(new String[1]);
		} else {
			return null;
		}
	}

}
